//
//  ZJMusicDetailViewController.m
//  BreadTravel
//
//  Created by 张健 on 16/1/4.
//  Copyright © 2016年 蓝鸥科技. All rights reserved.
//

#import "ZJMusicDetailViewController.h"
#import "ZJMusicModel.h"
#import "ZJPlayerModel.h"
#import "STKAudioPlayer.h"
@interface ZJMusicDetailViewController ()<STKAudioPlayerDelegate>

@property(nonatomic,strong)UIButton *nextButton;//下一首
@property(nonatomic,strong)UIButton *lastButton;//上一首
@property(nonatomic,strong)UIButton *playButton;//播放
@property(nonatomic,strong)UIButton *voiceButton;//声音调节
@property(nonatomic,strong)UILabel *timeLabel;//当前时间
@property(nonatomic,strong)UILabel *allTimeLabel;//总时间
@property(nonatomic,strong)UILabel *nameLabel;//歌曲名
@property(nonatomic,strong)UILabel *singerLabel;//歌手名
@property(nonatomic,strong)UISlider *progressSlider;//进播放度条
@property(nonatomic,strong)UISlider *voiceSlider;//声音进度
@property(nonatomic,strong)NSTimer *timer;//定时器
@property(nonatomic,strong)UIImageView *headImageView;
@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,strong)UIView *voiceView;//声音的位置
@property(nonatomic,strong)STKAudioPlayer *player;
@property(nonatomic,assign)NSInteger durMin;
@property(nonatomic,assign)NSInteger durSec;
@property (nonatomic,retain)CABasicAnimation *basicAnimation;

@end

int indexTwo = 0;

@implementation ZJMusicDetailViewController

//懒加载
- (CABasicAnimation *)basicAnimation {
    if (_basicAnimation == nil) {
        self.basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        //旋转一圈时长
        self.basicAnimation.duration = 30;
        //开始动画的起始位置
        self.basicAnimation.fromValue = [NSNumber numberWithInt:0];
        //M_PI是180度
        self.basicAnimation.toValue = [NSNumber numberWithInt:M_PI*2];
        //动画重复次数
        [self.basicAnimation setRepeatCount:NSIntegerMax];
        //播放完毕之后是否逆向回到原来位置
        [self.basicAnimation setAutoreverses:NO];
        //是否叠加（追加）动画效果
        [self.basicAnimation setCumulative:YES];
        //停止动画，速度设置为0
        self.headImageView.layer.speed = 1;
        //    self.ImageView.layer.speed = 0;
        [self.headImageView.layer addAnimation:self.basicAnimation forKey:@"basicAnimation"];
        
    }
    return _basicAnimation;
}

//视图已经消失时
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    //    [self.player stop];
    indexTwo = 0;
    //    [_myTime invalidate];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.player.state == STKAudioPlayerStatePlaying) {
//        [self.headImageView.layer removeAllAnimations];//移除动画
        self.basicAnimation = nil;
        [self basicAnimation];//开始动画
        
    }
    if (self.player.state == STKAudioPlayerStatePaused) {
        
        self.basicAnimation = nil;
    }
    
    //根据音量显示音量图片
    if (self.player.volume == 0) {
        [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang1"] forState:UIControlStateNormal];
    }else if(self.player.volume > 0.5){
        [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang3"] forState:UIControlStateNormal];
    }else{
        [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang2"] forState:UIControlStateNormal];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    self.view.backgroundColor = [UIColor blackColor];
    
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    //下面的初始化也可以,但设置不了enableVolumeMixer,就无法调节音量
    //self.player = [[STKAudioPlayer alloc] init];
    self.player.delegate = self;
    self.player.volume = 0.5;
    //基础控件
    [self createSubViews];
    
    [self playMusic];
}

#pragma mark 显示总播放时长和当前进度
-(void)track
{
    
    self.progressSlider.maximumValue = self.player.duration;//音乐总共时长
    self.progressSlider.value = self.player.progress;//当前进度
    
    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    self.durMin = (NSInteger)self.player.duration / 60;//总秒
    self.durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", proMin, proSec];
    self.allTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",self.durMin,self.durSec];
    
}

#pragma mark 播放音乐
- (void)playMusic{
    
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%ld", self.trackId];
    [self.player pause];
    [self.headImageView.layer removeAllAnimations];
    _basicAnimation = nil;
    [AFNetworkTool getUrl:string body:nil result:HXJSON headerFile:nil success:^(id result) {
        
        NSMutableDictionary *dic = result;
        ZJPlayerModel *playModel = [[ZJPlayerModel alloc]init];
        [playModel setValuesForKeysWithDictionary:dic];
        [self.player play:playModel.playUrl64];
        
        NSURL *url = [NSURL URLWithString:playModel.coverLarge];
        [self.headImageView sd_setImageWithURL:url placeholderImage:IMAGE];
        [self.bgImageView sd_setImageWithURL:url placeholderImage:IMAGE];
        self.nameLabel.text = playModel.title;
        self.singerLabel.text = playModel.albumTitle;
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        
    } failure:^(NSError *error) {
        
        
    }];
}

#pragma mark 播放进度条的方法
-(void)progressSlider:(UISlider *)slider {
    if (self.player) {
    
        [self.player seekToTime:slider.value];
    }
}



#pragma mark 拖动音量进度条的方法
-(void)voiceSlider:(UISlider *)slider {
    
    self.player.volume = slider.value;
    if (slider.value == 0) {
        [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang1"] forState:UIControlStateNormal];
    }else if(slider.value > 0.5){
        [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang3"] forState:UIControlStateNormal];
    }else{
        [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang2"] forState:UIControlStateNormal];
    }
}

#pragma mark 音量键
- (void)voiceButtonAction{
    self.voiceView.hidden = NO;
    [self.voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.voiceButton.mas_top);
        make.height.mas_equalTo(100);
        make.width.mas_equalTo(20);
        make.left.equalTo(self.voiceButton).offset(-1);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.voiceView.hidden = YES;
    });
    
}


#pragma mark 暂停/播放
- (void)playButtonAction{
    
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        
        [self.player resume];//继续
        //开始旋转
        //得到view当前动画时间偏移量
        CFTimeInterval stopTime = [self.headImageView.layer timeOffset];
        //初始化开始时间
        self.headImageView.layer.beginTime = 0;
        //初始化时间偏移量
        self.headImageView.layer.timeOffset = 0;
        //设置动画速度
        self.headImageView.layer.speed = 1;
        //计算时间差
        CFTimeInterval tempTime = [self.headImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        //重新设置动画开始时间
        self.headImageView.layer.beginTime = tempTime;
        
    }else if (self.player.state == STKAudioPlayerStatePlaying){
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang2"] forState:UIControlStateNormal];
        
        [self.player pause];
        CFTimeInterval stopTime = [self.headImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        //停止动画，速度设置为0
        self.headImageView.layer.speed = 0;
        //设置时间偏移量
        self.headImageView.layer.timeOffset = stopTime;
    }
}

#pragma mark 下一首
- (void)nextButtonAction{
    
    self.indexPath++;
    //如果点击的下标大于数组个数 吧下标改为0
    if (self.indexPath == self.infoArray.count) {
        
        self.indexPath = 0;
    }
    [self.player pause];
    ZJMusicModel *model = [self.infoArray objectAtIndex:self.indexPath];
    self.trackId = model.trackId;
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge]];
    [self playMusic];
    indexTwo = 0;
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
}

#pragma mark 上一首
- (void)lastButtonAction{
    
    self.indexPath--;
    if (self.indexPath < 0) {
        
        self.indexPath = self.infoArray.count - 1;
    }
    [self.player pause];
    ZJMusicModel *model = [self.infoArray objectAtIndex:self.indexPath];
    self.trackId = model.trackId;
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge]];
    [self playMusic];
    indexTwo = 0;
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
    
}

#pragma mark 点击上一曲或下一曲时,重新传值给trackId,重写此方法,再调用播放方法
-(void)setTrackId:(NSInteger)trackId
{
    if (self.trackId != trackId) {
        _trackId = trackId;
        [self playMusic];
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
    }
}

#pragma mark 创建基础控件
- (void)createSubViews{
    
    self.bgImageView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:self.bgImageView];
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:effect];
    
    blurView.alpha = 1;
    
    [self.bgImageView addSubview:blurView];
    
    [blurView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.bgImageView);
    }];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(15, 20+10, 20, 20);
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"add_new_poi_back_btn"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    
    self.nameLabel = [[UILabel alloc]init];
    //    self.nameLabel.text = @"落叶归根";
    self.nameLabel.font = [UIFont boldSystemFontOfSize:19];
    self.nameLabel.textColor = [UIColor whiteColor];
    self.nameLabel.numberOfLines = 2;
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    //    self.nameLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(50);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(300);
        make.height.mas_equalTo(46);
    }];
    self.singerLabel = [[UILabel alloc]init];
    //    self.singerLabel.text = @"—— 王力宏 ——";
    self.singerLabel.textColor = [UIColor whiteColor];
    self.singerLabel.textAlignment = NSTextAlignmentCenter;
    //    self.singerLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.singerLabel];
    [self.singerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.nameLabel.mas_bottom).offset(20);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(200);
    }];
    
    self.headImageView = [[UIImageView alloc]init];
    self.headImageView.backgroundColor = [UIColor grayColor];
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.cornerRadius = 110;
    [self.view addSubview:self.headImageView];
    [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(220);
        make.height.mas_equalTo(220);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.singerLabel.mas_bottom).offset(50);
    }];
    
    self.timeLabel = [[UILabel alloc]init];
    //    self.timeLabel.text = @"00:00";
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.font = [UIFont systemFontOfSize:15];
    //    self.timeLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(12);
        make.top.equalTo(self.headImageView.mas_bottom).offset(100);
        make.width.mas_equalTo(50);
    }];
    
    self.allTimeLabel = [[UILabel alloc]init];
    //    self.allTimeLabel.text = @"03:24";
    self.allTimeLabel.textColor = [UIColor whiteColor];
    self.allTimeLabel.textAlignment = NSTextAlignmentRight;
    self.allTimeLabel.font = [UIFont systemFontOfSize:15];
    //    self.allTimeLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.allTimeLabel];
    [self.allTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(-12);
        make.top.equalTo(self.timeLabel);
        make.width.equalTo(self.timeLabel);
    }];
    
    self.progressSlider = [[UISlider alloc]init];
    self.progressSlider.minimumTrackTintColor = [UIColor colorWithRed:0.1117 green:1.0 blue:0.5344 alpha:1.0];
    //    [self.progressSlider setThumbImage:[UIImage imageNamed:@"clock_gray_big"] forState:UIControlStateNormal];
    [self.progressSlider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.progressSlider];
    [self.progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.timeLabel.mas_right);
        make.right.equalTo(self.allTimeLabel.mas_left);
        make.centerY.equalTo(self.timeLabel);
    }];
    //播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    [self.playButton addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playButton];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.progressSlider.mas_bottom).offset(35);
    }];
    //上一首按钮
    self.lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.lastButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shangyishou-3"] forState:UIControlStateNormal];
    [self.lastButton addTarget:self action:@selector(lastButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.lastButton];
    [self.lastButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.playButton.mas_left).offset(-20);
        make.centerY.equalTo(self.playButton);
    }];
    //下一首按钮
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.nextButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xiayishou"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextButton];
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.playButton.mas_right).offset(20);
        make.centerY.equalTo(self.playButton);
    }];
    
    self.voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.voiceButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yinliang1"] forState:UIControlStateNormal];
    [self.voiceButton addTarget:self action:@selector(voiceButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.voiceButton];
    [self.voiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.allTimeLabel.mas_top).offset(-20);
        make.right.mas_equalTo(-30);
    }];
    
    //声音view
    self.voiceView = [[UIView alloc]init];
    self.voiceView.backgroundColor = [UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:1];
    self.voiceView.layer.masksToBounds = YES;
    self.voiceView.layer.cornerRadius = 7;
    //    self.voiceView.alpha = 0.5;
    [self.view addSubview:self.voiceView];
    
    
    //声音进度条
    self.voiceSlider = [[UISlider alloc]init];
    [self.voiceSlider setThumbImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    self.voiceSlider.minimumTrackTintColor = [UIColor colorWithRed:0.1117 green:1.0 blue:0.5344 alpha:1.0];
    [self.voiceSlider addTarget:self action:@selector(voiceSlider:) forControlEvents:UIControlEventValueChanged];
    [self.voiceSlider setThumbImage:[UIImage imageNamed:@"iconfont-huakuai"] forState:UIControlStateNormal];
    self.voiceSlider.value = self.player.volume;
    self.voiceSlider.transform = CGAffineTransformMakeRotation(M_PI*1.5);
    [self.voiceView addSubview:self.voiceSlider];
    [self.voiceSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.voiceView);
        make.height.equalTo(self.voiceView);
        make.top.equalTo(self.voiceView).offset(1);
        make.width.equalTo(self.voiceView.mas_height);
    }];
}


#pragma mark - 一些协议方法
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId{
    
    NSLog(@"aaaaa");
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId{
    
    NSLog(@"bbbbb");
}


-(void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    if (state == STKAudioPlayerStateStopped) {
        [self nextButtonAction];
    }
    if (state == STKAudioPlayerStatePlaying) {
        [self basicAnimation];
        
    }
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    
    NSLog(@"ccccc");
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    
    NSLog(@"ddddd");
}

#pragma mark - 创建单利,确保每次只初始化一个VC
+(instancetype)shareDetailViewController
{
    static ZJMusicDetailViewController *listenVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        listenVC = [[ZJMusicDetailViewController alloc]init];
    });
    return listenVC;
}

#pragma mark 返回按钮
- (void)buttonAction:(UIButton *)but{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
    

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
